import cgi
import datetime
import wsgiref.handlers


from google.appengine.api import users
from google.appengine.ext import webapp
from models import *
import os
from google.appengine.ext.webapp import template
import uuid

from base_action import BaseAction

def getTemplatePath(template_name):
    path = os.path.join( os.path.dirname(__file__), template_name )
    return path

class Home(BaseAction):
    def get(self):
        flea_servers = None
        user = users.get_current_user()
        if self.request.get( "p" ) == '':
            page_index = 0
        else:
            page_index = int( self.request.get( "p" ) )
        page_size = int( "10" )
        page_offset = int( page_index * page_size )
        
        if user:
            flea_servers = Flea_Server.gql("WHERE owner = :1", user).fetch( page_size, page_offset )
        else:
            flea_servers = Flea_Server.all().fetch( page_size, page_offset )
        
        self.viewdata( 'flea_servers',  flea_servers  )
        self.response.out.write( template.render( getTemplatePath( 'template/home.html' ), self.get_viewdata() ))

class PublicServer(BaseAction):
    def get( self ):
        public_visible = 'Public'
        flea_servers = Flea_Server.gql( "WHERE visible = :1", public_visible )
        self.viewdata( 'flea_servers', flea_servers  )
        self.response.out.write( template.render( getTemplatePath( 'template/public_server.html' ), self.get_viewdata() ) )

class Add(BaseAction):
    def get(self):
        self.response.out.write( template.render( getTemplatePath( 'template/add.html' ), self.get_viewdata() ))
    
    def post(self):
        user = users.get_current_user()
        if user:
            _server_name = self.request.get( "server_name" )
            _visible = None
            if self.request.get( "visible" ):
                _visible = 'Public'
            else:
                _visible = 'Private'
            
            uuid_value = str( uuid.uuid4() )
            flea_server = Flea_Server( owner = users.get_current_user(), server_name = _server_name, uuid = uuid_value, visible = _visible )
            flea_server.put()
            self.redirect( "/" )
        else:
            self.redirect( users.create_login_url("/") )

class Link(webapp.RequestHandler):
    def get(self):
        ip_address = self.request.remote_addr
        uuid = self.request.get( "uuid" )
        matched_flea_server = Flea_Server.gql( "where uuid = :1", uuid  ).get()
        
        if matched_flea_server  is not None:
            from datetime import datetime
            matched_flea_server.last_active_time = datetime.now()
            matched_flea_server.ip_address = ip_address
            matched_flea_server.put()
            self.response.out.write( matched_flea_server )
        else:
            self.response.out.write( "No server mantched" )

class Export(webapp.RequestHandler):
    def get(self):
        uuid = self.request.get( 'uuid' )
        flea_server = Flea_Server.gql( "WHERE uuid = :1", uuid )
        file_name = 'test'
        self.response.headers['Content-Type'] = 'application/octet-stream'
        self.response.headers['content-disposition'] = 'attachment; filename=' + file_name + '.py'
        
        template_values = {
            'uuid' : uuid,
        }
        path = os.path.join( os.path.dirname(__file__), 'template/script_template.txt' )
        self.response.out.write( template.render( path, template_values ) )
        
class Delete( webapp.RequestHandler ):
    def get(self):
        uuid = self.request.get( 'uuid' )
        flea_server = Flea_Server.gql( "WHERE uuid = :1", uuid ).get()
        flea_server.delete()
        self.redirect("/")
